package com.geek.javase.ch17.work.tcpwork.tcp07v2;

import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.util.concurrent.CountDownLatch;

/**
 * @Desc 客户端
 * @Author
 * @Date 2025/11/10
 */
public class TCPClient {

    public static void main(String[] args) {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1" , 8899);
            System.out.println("----------- 客户端已上线 -----------");

            //读
            new Thread(new ReadThread(socket , countDownLatch)).start();
            //写
            new Thread(new WriterThread(socket , countDownLatch)).start();

            //阻塞
            countDownLatch.await();
        } catch (ConnectException e){
            System.out.println("连接被拒！");
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
